package com.primb.bench.project.init.activity;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.TextView;

import com.flyco.dialog.widget.NormalDialog;
import com.primb.baselibs.util.NetworkUtils;
import com.primb.baselibs.util.PreferencesUtils;
import com.primb.baselibs.view.loading.SpotsDialog;
import com.primb.bench.R;
import com.primb.bench.base.BaseActivity;
import com.primb.bench.base.IApplication;
import com.primb.bench.common.constant.AppConstant;
import com.primb.bench.project.init.contract.LoginContract;
import com.primb.bench.project.init.entity.LoginEntity;
import com.primb.bench.project.init.presenter.LoginPresenterImpl;
import com.tbruyelle.rxpermissions.RxPermissions;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by Chen on 2017/4/13.
 * 功能描述：
 */

public class LoginActivity extends BaseActivity implements LoginContract.View {


    @BindView(R.id.et_user)
    EditText etUser;
    @BindView(R.id.et_pwd)
    EditText etPwd;
    @BindView(R.id.tv_company_english)
    TextView tvCompanyEnglish;
    private SpotsDialog dialog;
    private LoginContract.Presenter mPresenter;
    private int count = 0;

    @Override
    protected void onBasePreLayout() {
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
    }

    @Override
    protected int onBaseLayoutId(@Nullable Bundle savedInstanceState) {
        return R.layout.activity_login;
    }

    @Override
    protected void onBaseBindView() {
        String account = PreferencesUtils.getString(this, "account");
        if (account != null && !TextUtils.isEmpty(account))
            etUser.setText(account);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        tvCompanyEnglish.setText("CopyRight © 2011-" + calendar.get(Calendar.YEAR) + " PRIME.ALL_AROUND RIGHTS Reserved");
    }

    @Override
    protected void onLoadData() {
        mPresenter = new LoginPresenterImpl(this, this);
        RxPermissions rxPermissions = new RxPermissions(this);
        if (!rxPermissions.isGranted(Manifest.permission.READ_EXTERNAL_STORAGE) ||
                !rxPermissions.isGranted(Manifest.permission.READ_PHONE_STATE)) {
            NormalDialog dialog = showAlterDialogTwo("请求权限", "请确认使用APP的必要权限");
            dialog.setOnBtnClickL(() -> {
                dialog.dismiss();
            }, () -> {
                rxPermissions.request(Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.READ_PHONE_STATE).subscribe(aBoolean -> {
                    if (aBoolean) {
                        showToast("请求成功");
                    } else {
                        showToast("请求权限失败");
                    }
                });
                dialog.dismiss();
            });
        }
        ArrayList<String> dataList = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            dataList.add(i + "");
        }

        for (int i = 0; i < dataList.size(); i++) {
            if (i == 3) {
                dataList.remove(i);
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (etPwd != null) {
            etPwd.setText("");
        }
    }

    @OnClick({R.id.layout_login_icon, R.id.btn_login})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.layout_login_icon:
                count++;
                if (count > 7) {
                    startActivity(new Intent(this, SettingActivity.class));
                    count = 0;
                }
                break;
            case R.id.btn_login:
                if (NetworkUtils.isNetworkConnected(this)) {
                    mPresenter.start();
                } else {
                    showError("无网络连接，请连接网络后重试");
                }
                break;
        }
    }

    @Override
    public String getAccountStr() {
        return etUser.getText().toString();
    }

    @Override
    public String getPwdStr() {
        return etPwd.getText().toString();
    }

    @Override
    public void showLoading() {
        dialog = new SpotsDialog(this, "登录中");
        dialog.show();
    }

    @Override
    public void hideLoading() {
        if (dialog != null) {
            dialog.dismiss();
            mPresenter.onRecycle();
        }
    }

    @Override
    public void showError(String message) {
        showToast(message);
    }

    @Override
    public boolean isEmpty(String account, String pwd) {
        if (TextUtils.isEmpty(account) || TextUtils.isEmpty(pwd)) {
            return true;
        }
        PreferencesUtils.putString(this, "account", account);
        return false;
    }

    @Override
    public void intentToMain(LoginEntity entity) {
        if (entity.isSuccess()) {
            AppConstant.USER_NAME = entity.getData().getUserName();
            AppConstant.USER_NAME_ID = entity.getData().getUserId();
            AppConstant.USER_PART_ID = entity.getData().getOrgId();
            AppConstant.USER_PART_NAME = entity.getData().getOrgName();
            AppConstant.ROLE_LEVEL = entity.getData().getRoleLevel();
            if (AppConstant.USER_NAME != null && !TextUtils.isEmpty(AppConstant.USER_NAME)
                    && AppConstant.ROLE_LEVEL != null && !TextUtils.isEmpty(AppConstant.ROLE_LEVEL)
                    && AppConstant.USER_PART_ID != null && !TextUtils.isEmpty(AppConstant.USER_PART_ID)
                    && AppConstant.USER_PART_NAME != null && !TextUtils.isEmpty(AppConstant.USER_PART_NAME)) {
                Intent intent = new Intent(this, MainActivity.class);
                intent.putExtra("info", entity.getData());
//        Intent intent = new Intent(this, WebOfficeActivity.class);
                startActivity(intent);
//                this.finish();
            }
        } else {
            showError(entity.getMsg());
        }
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            NormalDialog dialogExit = showAlterDialogTwo("退出提示", "是否退出登录？");
            dialogExit.setOnBtnClickL(null, () -> exit());
        }
        return false;
    }
}
